package com.example.lending.ViewModel.Repository;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.lending.Model.Borrow;
import com.example.lending.Model.Dao.BorrowDao;
import com.example.lending.Model.Database;

import java.util.List;

public class BorrowRepository {
    private LiveData<List<Borrow>>allBorrowLive;
    private BorrowDao borrowDao;

    public BorrowRepository(Context context) {
        Database borrowDatabase = Database.getDatabase(context.getApplicationContext());
        borrowDao = borrowDatabase.getBorrowDao();
        allBorrowLive = borrowDao.getAllBorrowLive();
    }
    public LiveData<List<Borrow>>getAllBorrowLive(){
        return allBorrowLive;
    }
    public LiveData<List<Borrow>>findBorrowWithPattern(String pattern){
        return borrowDao.findBorrowWithPattern("%"+pattern+"%");
    }

    public void insertBorrows(Borrow... borrows){
        new InsertAsyncTask(borrowDao).execute(borrows);
    }
    public void updataBorrows(Borrow... borrows){
        new UpdataAsyncTask(borrowDao).execute(borrows);
    }
    public void deleteBorrows(Borrow... borrows){
        new InsertAsyncTask(borrowDao).execute(borrows);
    }
    public void deleteAllBorrows(Void... voids){
        new DeleteAllAsyncTask(borrowDao).execute();
    }


    static class InsertAsyncTask extends AsyncTask<Borrow,Void,Void> {
        private BorrowDao borrowDao;

        public InsertAsyncTask(BorrowDao borrowDao) {
            this.borrowDao = borrowDao;
        }

        @Override
        protected Void doInBackground(Borrow... borrows) {
            borrowDao.insertBorrow(borrows);//放到后台执行

            return null;
        }
    }

    static class UpdataAsyncTask extends AsyncTask<Borrow,Void,Void> {
        private BorrowDao borrowDao;

        public UpdataAsyncTask(BorrowDao borrowDao) {
            this.borrowDao = borrowDao;
        }

        @Override
        protected Void doInBackground(Borrow... borrows) {
            borrowDao.updataBorrow(borrows);//放到后台执行

            return null;
        }
    }

    static class DeleteAsyncTask extends AsyncTask<Borrow,Void,Void> {
        private BorrowDao borrowDao;

        public DeleteAsyncTask(BorrowDao borrowDao) {
            this.borrowDao = borrowDao;
        }

        @Override
        protected Void doInBackground(Borrow... borrows) {
            borrowDao.deleteBorrow(borrows);//放到后台执行

            return null;
        }
    }

    static class DeleteAllAsyncTask extends AsyncTask<Void,Void,Void> {
        private BorrowDao borrowDao;

        public DeleteAllAsyncTask(BorrowDao borrowDao) {
            this.borrowDao = borrowDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            borrowDao.deleteAllBorrow();//放到后台执行

            return null;
        }
    }


}
